using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Godot;
using Nett;

namespace Arcane.Source.Data
{
    public static class LoadUtil
    {
        public static void LoadRecursive<R>(string loadDir, Action<string, R> loadFunc, Func<string, bool> filter, string prefix = null)
            where R : Resource
        {
            using var acc = DirAccess.Open(loadDir);
            foreach (var file in acc.GetFiles().Where(filter))
            {
                if (GD.Load($"{loadDir}/{file}") is R res)
                {
                    var texName = file.GetBaseName();
                    loadFunc(prefix != null ? prefix + texName : texName, res);
                }
            }

            foreach (var dir in acc.GetDirectories())
            {
                LoadRecursive($"{loadDir}/{dir}", loadFunc, filter, prefix != null ? $"{prefix}{dir}/" : $"{dir}/");
            }
        }

        public static IEnumerable<(StringName, TomlTable)> LoadTomlFiles(string loadDir)
        {
            using var acc = DirAccess.Open(loadDir);
            foreach (var file in acc.GetFiles().Where(name => name.EndsWith(".toml")))
            {
                var name = file.GetBaseName();

                var doc = Toml.ReadString(FileAccess.GetFileAsString(loadDir.PathJoin(file)));
                yield return (name, doc);
            }
        }
    }
}